<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
  <style>
    #photo-img {
      width: 300px;
      height: 300px;
    }

    #photo {
      display: none;
    }
  </style>
</head>

<body>
  <form action="dealregister.php" method="post" enctype="multipart/form-data">
    请输入用户名:
    <input type="text" name="username" id="username"><span class="reg-info"></span><br>
    请选择照片：<img src="./images/back.jpg" id="photo-img"><input type="file" id="photo" name="photo"><br>
    请输入验证码: <input type="text" name="code">
    <img src="code.php" style="width: 230px;height:50px" id="code-img" />
    <a href="#" id="change">看不清楚，换一张</a>
    <br>
    <button>提交</button>

  </form>
  <script>
    const a = document.querySelector("#change");
    a.onclick = change;

    function change(e) {
      //1. 阻止a默认行为，不让a进行跳转
      e.preventDefault();
      const codeImg = document.querySelector("#code-img");
      codeImg.src = "code.php?code=" + Math.random()
    }
    const usernameObj = document.querySelector("#username");
    usernameObj.onblur = function(e) {
      $.ajax({
        url: "checkUserName.php",
        method: "post",
        data: {
          username: $("#username").val()
        },
        success: (res) => {
          const result = JSON.parse(res);
          const spanEle = document.querySelector(".reg-info");
          if (result.code == 200) {
            //用户名可以使用
            spanEle.innerHTML = "(用户名可使用)";
            spanEle.style.color = "green"
          } else {
            //用户名不可以使用
            spanEle.innerHTML = "(用户名被占用，请重新输入)";
            spanEle.style.color = "red"
          }
        }


      });
    }
    $("#photo").change(function() {
      //获取用户上传的图片文件
      const file = this.files[0];
      //显示图片
      //读取图片信息，把数据发送给img元素
      const reader = new FileReader();
      //读取图片文件
      reader.readAsDataURL(file);
      //添加一个异步事件
      reader.onload = function() {
        //获取图片元素
        const photoImgEle = document.querySelector("#photo-img");
        //把图片数据发送给img的src
        photoImgEle.src = this.result;
      }

    })
    $("#photo-img").click(function() {
      $("#photo").click();
    })
  </script>
</body>

</html>